import 'package:intl/intl.dart';
import 'package:xuance/bean/TimeEnum.dart';

DateTime? string2Date(String dateStr,
    {String pattern = "yyyy-MM-dd HH:mm:ss"}) {
  final formatter = DateFormat(pattern);
  try {
    return formatter.parse(dateStr);
  } catch (e) {
    return null;
  }
}

String? date2String(DateTime date, {String pattern = "yyyy-MM-dd HH:mm:ss"}) {
  final formatter = DateFormat(pattern);
  try {
    return formatter.format(date);
  } catch (e) {
    print(e);
    return null;
  }
}

List<String> getTime(TimeEnum type) {
  var now = DateTime.now();
  var startTime = "";
  switch (type) {
    case TimeEnum.hour:
      startTime = "${date2String(now.subtract(const Duration(hours: 1)))}";
      break;
    case TimeEnum.day:
      startTime = "${date2String(now.subtract(const Duration(hours: 24)))}";
      break;
    case TimeEnum.week:
      startTime = "${date2String(now.subtract(const Duration(days: 7)))}";
      break;
    default:
      startTime = "${date2String(now.subtract(const Duration(days: 30)))}";
  }

  var endTime = date2String(now)!;
  return [startTime, endTime];
}
